<template>
	<view class="tui-center">
		<uni-nav-bar fixed left-icon="back" :title="'购物车('+carList.length+')'"
					 leftClick
					 @click-left="clickLeft()"></uni-nav-bar>
		<!-- 空白页 -->
		<view v-if="!carList.length" class="empty">
			<image src="/static/image/emptyCart.jpg" mode="aspectFit"></image>
			<view class="empty-tips">空空如也</view>
		</view>
		<view class="card-mag" v-else>
			<view class="car-body">
				<view class="tui-flex br-b" v-for="(item, index) in carList" :key="index" @longpress="logoTime(index)">
					<uni-icons
						class="checkbox"
						type="checkbox-filled"
						size="44"
						:color="item.checked? '#6CB041': '#C0C4CC'"
						@click="checkClick('item', index)"
						></uni-icons>
					<view style="width: 23%" @tap="nvTo('/pagesA/ticket/components/ticketDetail?id='+item.spuId)">
						<image class="card-img" :src="item.pic" mode="aspectFill"></image>
					</view>
					<view class="tui-card-align">
						<view  @tap="nvTo('/pagesA/ticket/components/ticketDetail?id='+item.spuId)">
							<view class="tui-car-title">{{item.productName}}</view>
							<view class="tui-text-gray">{{item.attr_val}}</view>
							<!--<view class="tui-car-weight">{{item.weight}}kg</view>-->
						</view>
						<view class="car-flex">
							<view class="tui-text-pric">￥<text>{{item.price}}</text></view>
							<view class="tui-number-box">
                                <number-box :value="item.num"
                                            :min="0"
                                            :disabled="true"
                                            :step="1"
                                            :data="item"
                                            @change="numberChange($event, item, index)">
                                </number-box>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="action-section car-body">
				<view class="checkboxs">
					<uni-icons
						class="checkbox-ioc"
						type="checkbox-filled"
						:color="allChecked? '#6CB041': '#C0C4CC'"
						size="46"
						@click="checkClick('all')"
					></uni-icons>
					<view class="clear-btn" :class="{show: allChecked}" @click="clearCart">清空</view>
				</view>
				<view style="display: flex;">
					<view class="total-box">
						<view>
							合计：<text class="price">¥{{ total }}</text>
						</view>
						<!--<text class="coupon" v-if="allChecked">
							积分抵扣： <text>{{deduction}}</text>元
						</text>-->
					</view>
					<button type="primary" class="no-border confirm-btn" @click="createOrder">去结算</button>
				</view>
			</view>
		</view>
		<!-- 登录提示 -->
		<uni-login-model></uni-login-model>
	</view>
</template>

<script>
	import numberBox from '@/components/uni-number-box/number-box.vue'
	import uniIcons from '@/components/uni-icons/uni-icons.vue'
	import empty from '@/components/empty.vue'
    import uniLoginModel from '@/components/uni-login-model/uni-login-model.vue'
	
	export default {
		name: 'card',
		components: {
			uniIcons, numberBox, empty, uniLoginModel
		},
		data() {
			return {
				total: 0, //总价格
				allChecked: true, //全选状态  true|false
				carList: [],
				deduction: 15,
                flag: ''
			}
		},
		onLoad(option) {
		    this.flag = option.flag
			this.getList()
		},
		methods: {
			getList() {
				let that = this
                that.carList = []
                uni.showLoading()
				this.$api.api('cart.index').then(res => {
                    uni.hideLoading();
                    if (res.code == 200) {
                        res.data.forEach(item=>{
                            this.$set(item,'checked', true)
                            that.carList.push(item);
                        })
                        this.calcTotal();
					} else {
                        this.$api.msg(res.message)
					}
				}).catch(error => {
                    this.$api.msg(error.message)
				})
			},
			checkClick(type, index) {
				if(type === 'item'){
					this.carList[index].checked = !this.carList[index].checked;
				}else{
					const checked = !this.allChecked
                    this.carList.forEach(item=>{
						item.checked = checked;
					})
					this.allChecked = checked;
				}
				this.calcTotal(type);
			},
			//清空
			clearCart(){
			    let than = this
				uni.showModal({
					content: '清空购物车？',
					success: (e)=>{
						if(e.confirm){
                            than.$api.api('cart.clear').then(res => {
                                if (res.code == 200) {
                                    than.$store.dispatch('getUserInfo')
                                    than.carList = []
                                    than.getList()
								} else {
                                    than.$api.msg(res.message)
								}
                            }).catch(error => {
                                than.$api.msg(error.message)
                            })
						}
					}
				})
			},
            minus(data, item) {
                console.log(data, item)
                this.carList.forEach(i => {
                    if (i.id == item.id) {
                        this.carList[i].num = data;
					}
				})
                this.calcTotal();
                let form = {
                    id: item.id,
                    num: data,
                    price: item.price,
                    pic: item.pic,
                    productId: item.productId,
                    productName: item.productName
                }
                this.$api.api('cart.upD', form).then(res => {
                    if (res.code == 200) {
                        // this.getList()
                    } else {
                        this.$api.msg(res.message)
                    }
                }).catch(error => {
                    this.$api.msg(error.message)
                })
            },
			//数量
			numberChange(e, item, index){
				this.carList[index].num = e;
				this.calcTotal();
                let form = {
                    id: item.id,
                    num: e,
                    price: item.price,
                    pic: item.pic,
                    productId: item.productId,
                    productName: item.productName
                }
                this.$api.api('cart.upD', form).then(res => {
                    if (res.code == 200) {
                    } else {
                        this.$api.msg(res.message)
                    }
                }).catch(error => {
                    this.$api.msg(error.message)
                })
			},
			//	长按
			logoTime(index) {
			    console.log(index)
				let row = this.carList[index];
				let id = row.productId;
				let than = this
				uni.showModal({
				    content: '确定要删除吗',
					success: (e)=>{
						if(e.confirm){
						    // uni.showLoading('请稍等')
                            uni.request({
                                url: `cart/delete/${id}`,
                                method: 'POST',
                                header: {
                                    'content-type': 'application/json',
                                    'Authorization': 'Bearer ' + uni.getStorageSync('token')
                                },
                                success: (res) => {
                                    than.getList()
                                    than.$store.dispatch('getUserInfo')
                                    // uni.hideLoading();
                                },
                                fail: (res) => {
                                    // uni.hideLoading();
                                    than.$api.msg(res.data.message)
                                }
                            })
						}
					}
				});
			},
			//计算总价
			calcTotal(){
				let total = 0;
				let checked = true;
                this.carList.forEach(item => {
					if(item.checked == true){
						total += item.num * item.price;
					}else if(checked == true){
						checked = false;
					}
				})
				this.allChecked = checked;
				this.total = Number(total.toFixed(2));
			},
			//创建订单
			createOrder(){
                this.carList.forEach(item => {
                    console.log(item.productId)
                    this.$set(item, 'skuId', item.productId)
				})
				console.log(JSON.stringify({data: this.carList}))
				uni.navigateTo({
					url: `/pagesA/card/pay?data=${JSON.stringify({
						data: this.carList,
						money: this.total
					})}`
				})
			},
			nvTo(url) {
				uni.navigateTo({
					url: url
				})
			},
            clickLeft() {
			    if (this.flag == 1) {
                    uni.navigateBack({delta:1,
                        success: function() {
                            this.$api.prePage().$vm.cartList(); // 执行前一个页面的刷新
                        }})
				} else {
                    uni.navigateBack({delta: 1})
				}
            }
		}
	}
</script>

<style lang="scss">
	.empty{
		position:fixed;
		left: 0;
		top:0;
		width: 100%;
		height: 100vh;
		padding-bottom:100rpx;
		display:flex;
		justify-content: center;
		flex-direction: column;
		align-items:center;
		background: #fff;
		image{
			width: 240rpx;
			height: 160rpx;
			margin-bottom:30rpx;
		}
		.empty-tips{
			display:flex;
			font-size: $uni-font-size-sm+2rpx;
			.navigator{
				color: $font-color-dark;
				margin-left: 16rpx;
			}
		}
	}
	.card-mag {
		padding: $uni-spacing-row-lg 0 150rpx;
		.car-body {
			margin: 0 $uni-spacing-row-sm + 5rpx;
			border-radius: $uni-border-radius-sm;
			background-color: $uni-bg-color;
			.br-b {
				display: flex;
				align-items: center;
				padding: $uni-spacing-row-lg 0;
				.checkbox {
					padding: $uni-spacing-row-base;
				}
				.card-img {
					width: 100%;
					height: 150rpx;
				}
				.tui-card-align {
					line-height: 2.1;
                    flex: 1;
					padding: 0 20rpx;
					.car-flex {
						display: flex;
						justify-content: space-between;
						align-items: center;
						.tui-text-pric {
							font-size: $uni-font-size-lg;
							font-weight: 500;
							color: $uni-color-error;
						}
					}
					.tui-car-title {
						font-size: $uni-font-size-md;
						font-weight: 500;
						text-overflow: ellipsis;
						white-space: nowrap;
						overflow: hidden;
					}
					.tui-text-gray {
						font-size: $uni-font-size-base;
						color: $font-color-dark;
					}
					.tui-car-weight {
						font-size: $uni-font-size-base;
						color: rgb(255, 146, 99);
					}
				}
			}
		}
		.action-section {
			position: fixed;
			left: $uni-spacing-row-sm + 5rpx;
			right: $uni-spacing-row-sm + 5rpx;
			bottom: 30rpx;
			z-index: 95;
			display: flex;
			justify-content: space-between;
			align-items: center;
			box-shadow: 0 0 8rpx 0 rgba(0,0,0,.2);
			.checkboxs {
				.checkbox-ioc {
					width: 52rpx;
					height: 100%;
					position:relative;
					z-index: 5;
					padding: 4rpx;
					background:#fff;
					border-radius: $uni-border-radius-circle;
				}
				.clear-btn {
					position:absolute;
					left: 40rpx;
					top: 26rpx;
					z-index: 4;
					width: 0;
					height: 48rpx;
					line-height: 52rpx;
					padding-left: 30rpx;
					font-size: $uni-font-size-base;
					color: #fff;
					background: #C0C4CC;
					border-radius:0 100rpx 100rpx 0;
					opacity: 0;
					transition: .2s;
					&.show{
						opacity: 1;
						width: 100rpx;
					}
				}
			}
			.total-box {
				margin-right: $uni-spacing-row-base;
				color: $font-color-dark;
				line-height: 1.4;
				.price {
					color: #e54d42;
					font-size: $uni-font-size-lg + 4rpx;
					font-weight: 600;
				}
				.coupon {
					color: #FFA200;
					font-size: $uni-font-size-sm;
				}
			}
			.confirm-btn {
				width: 200rpx;
				font-size: 36rpx;
				background-image: linear-gradient(to right, #6CB041 , #6CB041);
				border-radius: 0 30rpx 30rpx 0;
				height: 100rpx;
			}
		}
	}
</style>
